package com.yuncheng.spcyApi.spcyService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.flow.FlowNodeService;
import com.yuncheng.spcyApi.flow.SpcyFlowConstant;
import com.yuncheng.spcyApi.mapper.SpcyRsWjmbMapper;
import com.yuncheng.spcyApi.mapper.SpcySqsxBaiscMapper;
import com.yuncheng.spcyApi.mapper.SpcySqsxJobMapper;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.hbjc.BhbSqsxJbxxVo;
import com.yuncheng.spcyApi.vo.sqsx.SqsxHbsxZbrVo;
import com.yuncheng.spcyApi.vo.wjmb.SqsxWjmbVo;
import com.yuncheng.spcyApi.vo.hbjc.HbSqsxVo;
import org.apache.tomcat.jni.Local;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.DateConversionUtils;
import utils.Util;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 合并检查
 * @author hua
 */
@Service
public class SpcyHbjcService {

    private static final Logger log = LoggerFactory.getLogger(SpcyHbjcService.class);

    @Resource
    private BusService busService;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    private SpcySqsxBaiscMapper spcySqsxBaiscMapper;

    @Resource
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    private SpcySqsxJobMapper spcySqsxJobMapper;

    @Resource
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    private FlowNodeService flowNodeService;

    @Resource
    private ISysFlowNodeService sysFlowNodeService;

    @Resource
    private SpcyRsWjmbMapper spcyRsWjmbMapper;

    @Resource
    private SpcyFlfgService spcyFlfgService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private ISpcySqsxBczgjlService spcySqsxBczgjlService;

    /**
     * 验证是否为合并申请事项
     * @return true: 是
     */
    public boolean verifySqsxIsHbsqsx(String sqsxid, SpcySqsxBasic sqsx){
        Integer fhbsxzt = 0;
        if (sqsx == null){
            if (StringUtils.isBlank(sqsxid)){
                return false;
            }

            fhbsxzt = spcySqsxBaiscMapper.selectFhbsxztById(sqsxid);

        }else {
            fhbsxzt = sqsx.getFhbsxzt();

            if (fhbsxzt == null){
                fhbsxzt = spcySqsxBaiscMapper.selectFhbsxztById(sqsxid);
            }
        }

        if (fhbsxzt != null && fhbsxzt == 1){
            return true;
        }

        return false;
    }

    /**
     * 验证当前事项是否为被合并事项
     * @return true: 是
     */
    public boolean verifyBhbSqsxIsHbsqsx(String sqsxid, SpcySqsxBasic sqsx){
        if (sqsx == null){
            if (StringUtils.isBlank(sqsxid)){
                return false;
            }

            if (StringUtils.isNotBlank(spcySqsxBaiscMapper.selectFhbsxidsById(sqsxid))){
                return true;
            }else {
                return false;
            }
        }else {
            if (StringUtils.isBlank(sqsx.getFhbsxids())){
                return false;
            }else {
                return true;
            }
        }

    }

    /**
     * 合并事项
     * @param idsList 被合并的事项ids
     * @param job 当前流程任务
     * @param nowSqsx 当前流程对应的事项
     * @param hbsxmc 合并后的事项名称
     * @param dbrid 新环节待办人id
     * @param flowNode 指定流程环节
     */
    @Transactional(rollbackFor = Exception.class)
    public void hbsqsx(List<String> idsList,
                       SpcySqsxJob job,
                       SpcySqsxBasic nowSqsx,
                       String hbsxmc, String hbslbh, String hbjclx, String hbsqdbh,
                       HbSqsxVo param, String dbrid, SysFlowNode flowNode){

        // 待办人名称
        String dbr = busService.getZbrmcByZbrId(dbrid);

        /** 构建事项 */
        SpcySqsxBasic hbSqsx = this.initGenHbSqsx(nowSqsx, hbsxmc, hbslbh, hbjclx, hbsqdbh);
        hbSqsx.setFhbsxids(StringPatternUtils.convertListToDhString(idsList)); // 被合并事项ids
        hbSqsx.setFzbr(param.getZbrid());
        hbSqsx.setFjbrmc(busService.getZbrmcByZbrId(param.getZbrid()));
        hbSqsx.setFhbsxxbrid(param.getXbrid());

        String blr = GetCurrentUserUtils.getCurrentUserName();
        String blbm = GetCurrentUserUtils.getCurrentUserOrgName();

        // 添加合并事项
        spcySqsxBaiscService.save(hbSqsx);

        /** 新增合并的事项方案制定环节 */
        SpcySqsxJob newJob = flowNodeService.initNewJob(hbSqsx.getId(), dbrid, dbr, flowNode.getId(), flowNode.getFjdmc(), job.getFlcmc(), GetCurrentUserUtils.getCurrentUser(), "", "");
        spcySqsxJobService.save(newJob);

        for (String id : idsList) {

            /** 更新被合并事项的流程任务办结 */
            LambdaUpdateWrapper<SpcySqsxJob> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SpcySqsxJob::getFpid, id);
            updateWrapper.ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB);


            SpcySqsxJob beanJob = new SpcySqsxJob();
            beanJob.setFblyj(Optional.ofNullable(param.getOpinion()).orElseGet(()->"事项合并检查"));
            beanJob.setFblsj(new Date());
            beanJob.setFblzt(SpcyConstant.BLZT_YB);
            beanJob.setFbllx(SpcyConstant.BLLX_ZB);
            beanJob.setFblr(blr);
            beanJob.setFblbm(blbm);
            spcySqsxJobMapper.update(beanJob, updateWrapper);

            /** 被合并申请事项-挂起 */
            LambdaUpdateWrapper<SpcySqsxBasic> updateSxWrapper = new LambdaUpdateWrapper<>();
            updateSxWrapper.eq(SpcySqsxBasic::getId, id);

            SpcySqsxBasic updateSqsx = new SpcySqsxBasic();
            updateSqsx.setFlczt(SpcyFlowConstant.LCZT_SXGQ);
            updateSqsx.setFhbsxids(hbSqsx.getId());
            updateSqsx.setCreateTime(new Date());
            updateSqsx.setUpdateTime(new Date());
            spcySqsxBaiscMapper.update(updateSqsx, updateSxWrapper);

        }
    }

    /**
     * 复制当前事项的现场检查相关基本信息-到其他事项
     * */
    public Result copyHbsxJcqkzs(String sqsxid, String bhbsxid, boolean isJcqkzs, boolean isJcjl){
        if (StringUtils.isBlank(sqsxid)){
            return Result.error("事项参数为空！");
        }
        if (StringUtils.isBlank(bhbsxid)){
            return Result.error("选择参数为空！");
        }
        SpcySqsxBasic hbsqsx = spcySqsxBaiscMapper.selectSqsxXcjcById(sqsxid);
        if (hbsqsx == null){
            return Result.error("没有相匹配的数据！");
        }

        LambdaUpdateWrapper<SpcySqsxBasic> updateSxWrapper = new LambdaUpdateWrapper<>();
        updateSxWrapper.eq(SpcySqsxBasic::getId, bhbsxid);

        SpcySqsxBasic updateSqsx = new SpcySqsxBasic();

        if (isJcqkzs) {
            updateSqsx.setFjcqkzs(hbsqsx.getFjcqkzs());
        }

        if (isJcjl){
            updateSqsx.setFcyyzqx(hbsqsx.getFcyyzqx());
            updateSqsx.setFcyzyqx(hbsqsx.getFcyzyqx());
            updateSqsx.setFcyybqx(hbsqsx.getFcyybqx());

            updateSqsx.setFjcqxxm(hbsqsx.getFjcqxxm());
            updateSqsx.setFcyqtwt(hbsqsx.getFcyqtwt());


            updateSqsx.setFcyjl(hbsqsx.getFcyjl());
            updateSqsx.setFcyjg(hbsqsx.getFcyjg());
            updateSqsx.setFcyjcyj(hbsqsx.getFcyjcyj());
        }

        spcySqsxBaiscMapper.update(updateSqsx, updateSxWrapper);

        return Result.ok();
    }

    /**
     * 复制当前事项的附件到其他事项
     */
    public Result copyHbsxWj(String copyFileId, String targetSqsxId){
        if (StringUtils.isBlank(copyFileId)){
            return Result.error("文件参数为空！");
        }


        return Result.ok();
    }

    /**
     * 合并事项报告模板选择绑定事项-查询被合并事项列表
     * 排除已经绑定报告的事项
     * */
    public HttpResult queryBgBhbsxList(String sqsxid){
        if (org.apache.commons.lang3.StringUtils.isBlank(sqsxid)){
            return HttpResult.error("事项参数为空！");
        }

        return HttpResultVo.HttpResultList(this.selectNotBdBgMbSxList(sqsxid));
    }

    /**
     * 验证合并事项是否存在还没有绑定检查报告的子事项
     * @param sqsxid
     */
    public void verifyHbsxIsExistNotBdBgMbSx(String sqsxid){
        /** 验证合并事项 */
        if (verifySqsxIsHbsqsx(sqsxid, null)) {
            if (CollectionUtil.isNotEmpty(this.selectNotBdBgMbSxList(sqsxid))){
                throw new BusinessException("提交失败，存在事项还没有选择对应的检查报告！");
            }
        }
    }

    /**
     * 查询合并事项报告模板-没有绑定报告模板的事项列表
     */
    private List<BhbSqsxJbxxVo> selectNotBdBgMbSxList(String sqsxid){
        /** 已经选择报告模板的被合并事项 */
        List<String> bhbsxidsList = spcyRsWjmbMapper.selectFmblx3ByFsqsxid(sqsxid);

        /** 处理当前合并事项已经绑定的报告模板的事项ids */
        List<String> idsList = new ArrayList<>();
        for (String ids : bhbsxidsList){
            if (ids.contains(",")){
                for (String id : StringPatternUtils.getListByIds(ids)){
                    if (!idsList.contains(id)){
                        idsList.add(id);
                    }
                }
            }else {
                if (!idsList.contains(ids)){
                    idsList.add(ids);
                }
            }
        }

        if (CollectionUtil.isEmpty(idsList)) {
            return spcySqsxBaiscMapper.selectBhbsqsxListByFhbsxid(sqsxid);

        }else {

            return spcySqsxBaiscMapper.selectBhbsxListByIdsAndFhbsxid(idsList, sqsxid);
        }
    }

    /**
     * 获取审评查验流程
     * 指定环节的流程待办结点 (方案制作)
     * */
    public SysFlowNode getFlowNodeInFazz(String fywflcode){
        return this.getFlowNodeInCommon(fywflcode, SpcyFlowConstant.HJMC_FAZZ);
    }

    /** 获取审评查验流程
     *  指定环节的流程待办结点
     * */
    private SysFlowNode getFlowNodeInCommon(String fywflcode, String fhjmc){
        String flowCode = SpcyFlowConstant.getFlowCodeByYwflcode(fywflcode, SpcyConstant.SQSX_BASIC_XZSPZT_YES);

        List<SysFlowNode> nodeByCodeJdmc = sysFlowNodeService.getNodeByCodeJdmc(flowCode, fhjmc);
        if (CollectionUtil.isEmpty(nodeByCodeJdmc)){
            return null;
        }

        return nodeByCodeJdmc.get(0);
    }

    /**
     * 初始化构建合并事项
     * */
    private SpcySqsxBasic initGenHbSqsx(SpcySqsxBasic nowSqsx, String hbsxmc, String hbslbh, String hbjclx, String hbsqdbh){
        SpcySqsxBasic sqsx = new SpcySqsxBasic();
        BeanUtil.copyProperties(nowSqsx, sqsx);
        sqsx.setId(GetUuIdUtils.ReplaceUuId());
        sqsx.setFsxsqjbxxid(GetUuIdUtils.NotReplaceUuId());
        sqsx.setFsxmc(hbsxmc);
        sqsx.setFslbh(hbslbh);
        sqsx.setFjclx(hbjclx);
        sqsx.setFsqdbh(hbsqdbh);
        sqsx.setFsyts("0");
        sqsx.setFsysx("30");
        sqsx.setFwcsx(30);
        sqsx.setFhbsxzt(1); // 合并事项状态

        return sqsx;
    }

    /** 合并事项-方案审批提交- */
    @Async(value = "asyncNormalTask")
    public void ffSyncHbsxInfoByFasp(String sqsxid, SpcySqsxBasic sqsx){
        /** 同步事项基本信息 */
        this.ffHbsxTyXpjlToSubBhbSqsxByFasp(sqsxid);

        /** 同步选派记录 */
        this.ffHbsxCommonInfoToSubBhbSqsxByFasp(sqsxid, true);
    }

    /**
     * 合并事项-审批提交后-将选派记录进行分发
     * @param sqsxid 合并的事项id
     * @param isHbsx true: 为合并事项；false: 不执行
     */
    private void ffHbsxCommonInfoToSubBhbSqsxByFasp(String sqsxid, boolean isHbsx){
        if (StringUtils.isBlank(sqsxid)){
            return;
        }

        if (!isHbsx){
            return;
        }

        /*// 当前事项合并检查状态
        Integer hbsxzt = spcySqsxBaiscMapper.selectFhbsxztById(sqsxid);
        if (hbsxzt == null && !hbsxzt.equals(1)){
            return;
        }*/

        List<BhbSqsxJbxxVo> bhbSqsxList = spcySqsxBaiscMapper.selectBhbsqsxListByFhbsxid(sqsxid);

        List<SpcySqsxXpjl> tyXpList = spcySqsxXpjlService.getTyXpXpjlListNotOrder(sqsxid);
        if (CollectionUtil.isEmpty(tyXpList)){
            return;
        }

        List<SpcySqsxXpjl> batchInsertList = new ArrayList<>();

        for (BhbSqsxJbxxVo bhbsx : bhbSqsxList) {
            for (int i = 0; i < tyXpList.size(); i++) {
                SpcySqsxXpjl newBean = new SpcySqsxXpjl();
                BeanUtil.copyProperties(tyXpList.get(i), newBean);

                newBean.setId(GetUuIdUtils.NotReplaceUuId());
                newBean.setFsqsxid(bhbsx.getId());
                newBean.setFhbjczt(1); // 标识合并

                batchInsertList.add(newBean);
            }
        }

        // 批量插入被合并申请事项的选派记录
        spcySqsxXpjlService.batchInsertXpjlList(batchInsertList);
    }

    /**
     * 合并事项-审批提交后
     * 将合并事项相关信息同步
     * @param sqsxid 合并的事项id
     */
    private void ffHbsxTyXpjlToSubBhbSqsxByFasp(String sqsxid){
        // 合并事项
        SpcySqsxBasic hbsqsx = spcySqsxBaiscMapper.selectById(sqsxid);
        if (hbsqsx == null){
            return;
        }

        /** 同步更新-被合并申请事项-共用信息 */
        spcySqsxBaiscService.updateaBhbsxCommonInfoByHbsx(sqsxid, hbsqsx);
    }

    /** 合并事项-现场检查提交 */
    @Async(value = "asyncNormalTask")
    public void ffSyncHbsxInfoByXcjc(String sqsxid, SpcySqsxBasic sqsx){
        /** 将被合并申请事项恢复在办 */
        this.bhbsxRecoveryFlczt(sqsxid);

        /** 现场检查提交后-同步相关信息到被合并的事项中 */
        try {
            this.ffHbsxXcjcInfoToSubBhbSqsxByXcjc(sqsxid, null);
        }catch (Exception e){

        }

        /** 同步共用的文件记录-到每一个被合并的事项 */
        try {
            this.ffCommonWjjlToSubBhbSqsxByXcjc(sqsxid, sqsx);
        }catch (Exception e){

        }

        this.ffzgjl(sqsxid, sqsx);

        this.fflzjl(sqsxid, sqsx);
    }

    /**
     *
     */
    public void ffzgjl(String sqsxid, SpcySqsxBasic sqsx){
        try {


            List<SpcySqsxBczgjl> list = spcySqsxBczgjlService.list(new LambdaQueryWrapper<SpcySqsxBczgjl>()
                    .eq(SpcySqsxBczgjl::getFsqsxid, sqsxid));
            if (CollectionUtil.isEmpty(list)){
                return;
            }

            if (sqsx == null){
                sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
            }

            List<String> listByIds = StringPatternUtils.getListByIds(sqsx.getFhbsxids());

            for (String sxid : listByIds) {
                for (SpcySqsxBczgjl zg : list) {
                    zg.setId(GetUuIdUtils.NotReplaceUuId());
                    zg.setFsqsxid(sxid);
                    spcySqsxBczgjlService.save(zg);
                }
            }
        }catch (Exception e){

        }
    }

    public void fflzjl(String sqsxid, SpcySqsxBasic sqsx){
        try {


            List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                    .eq(SpcySqsxJob::getFpid, sqsxid)
                    .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                    .like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.LCMC_LIKE_SPCYLC));
            if (CollectionUtil.isEmpty(jobList)){
                return;
            }

            if (sqsx == null){
                sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
            }

            List<String> listByIds = StringPatternUtils.getListByIds(sqsx.getFhbsxids());

            for (String sxid : listByIds) {
                for (SpcySqsxJob job : jobList){
                    job.setId(GetUuIdUtils.NotReplaceUuId());
                    job.setFpid(sxid);
                    spcySqsxJobService.save(job);
                }
            }

        }catch (Exception e){

        }

    }

    /**
     * 现场检查提交后-同步相关信息到被合并的事项中
     * 同步（现场检查相关及报告、方案，检查问题、条款）
     * @param sqsxid
     * */
    private void ffHbsxXcjcInfoToSubBhbSqsxByXcjc(String sqsxid, SpcySqsxBasic hbsqsx){
        if (hbsqsx == null){
            hbsqsx = spcySqsxBaiscMapper.selectById(sqsxid);
            if (hbsqsx == null){
                return;
            }
        }

        /** 检查报告 */
        List<String> bhbsxids = StringPatternUtils.getListByIds(hbsqsx.getFhbsxids());
        List<SpcySqsxWjjl> bhbSxWjList = new ArrayList<>();

        /** 合并事项下的检查报告 */
        List<SpcyRsWjmb> bgList = spcyRsWjmbMapper.selectList(new LambdaQueryWrapper<SpcyRsWjmb>()
                .eq(SpcyRsWjmb::getFsqsxid, sqsxid)
                .eq(SpcyRsWjmb::getFmblx1, WjmlConstant.xcjcbg));
        for (String sxid : bhbsxids){
            for (SpcyRsWjmb mb : bgList) {

                if (!mb.getFmblx3().contains(sxid)) {
                    continue;
                }

                /** 存在两个合并事项,默认取第一个 */
                if (StringUtils.isNotBlank(mb.getFmblx3())
                        && mb.getFmblx3().contains(",")
                        && StringPatternUtils.getStringsByIds(mb.getFmblx3()).length > 1) {

                    /** 合并取第一个 */
                    String bhbsxid = StringPatternUtils.getStringsByIds(mb.getFmblx3())[0];
                    if (bhbsxid.equals(sxid)){
                        continue;
                    }

                    /** 现场检查相关信息 */
                    this.ffXcjcCommonInfoToSubBhbSqsx(sxid, spcySqsxBaiscMapper.selectSqsxXcjcById(bhbsxid));

                    /** 同步现场检查问题 */
                    spcyFlfgService.syncHbsqsxInfoZjAndWtAndTk(bhbsxid, sxid);

                    /** 检查报告相关文件 */
                    List<String> typeList = CollectionUtil.newArrayList(
                            WjmlConstant.xcjcbg,
                            WjmlConstant.xcjcqxjlb
                    );
                    List<SpcySqsxWjjl> jcbgList = spcySqsxWjjlService.findWjjlListByFwjlx1(typeList, bhbsxid);
                    for (SpcySqsxWjjl oldWjjl : jcbgList) {
                        /** 迁移文件和记录 */
                        this.convertMoveSqsxFile(oldWjjl, sxid);
                    }

                }
            }
        }

        /**
         * 分发检查方案
         */
        List<SpcySqsxWjjl> jcfaList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, sqsxid)
                .eq(SpcySqsxWjjl::getFwjlx1, WjmlConstant.jcfa));
        for (String sxid : bhbsxids) {
            /** 分发合并的事项方案-给对应事项发放文件 */
            List<SpcySqsxWjjl> filterFaList = jcfaList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFwjlx6()) && f.getFwjlx6().contains(sxid))
                    .collect(Collectors.toList());
            if (CollectionUtil.isEmpty(filterFaList)) {
                /** 如果方案不是合并的，就对被合并事项分发方案 */
                filterFaList = jcfaList.stream()
                        .filter(f -> StringUtils.isBlank(f.getFwjlx6()))
                        .collect(Collectors.toList());
            }

            for (SpcySqsxWjjl oldWjjl : filterFaList) {
                SpcySqsxWjjl bhbSxWj = new SpcySqsxWjjl();
                BeanUtil.copyProperties(oldWjjl, bhbSxWj);
                bhbSxWj.setId(GetUuIdUtils.NotReplaceUuId());
                bhbSxWj.setFwjlx6(SpcyCommonConstant.QY_WJCL_FBZ_HBSX);
                bhbSxWj.setFpid(sxid);

                bhbSxWj.setCreateTime(new Date());

                bhbSxWjList.add(bhbSxWj);
            }
        }

        if (CollectionUtil.isEmpty(bhbSxWjList)){
            return;
        }
        // 批量插入被合并申请事项文件记录
        spcySqsxWjjlService.saveBatch(bhbSxWjList);

    }

    /**
     * 同步现场检查相关信息-到对应的被合并事项
     * */
    private void ffXcjcCommonInfoToSubBhbSqsx(String updateSxId, SpcySqsxBasic hbsqsx){
        LambdaUpdateWrapper<SpcySqsxBasic> updateSxWrapper = new LambdaUpdateWrapper<>();
        updateSxWrapper.eq(SpcySqsxBasic::getId, updateSxId);

        SpcySqsxBasic updateSqsx = new SpcySqsxBasic();

        updateSqsx.setFjcqkzs(hbsqsx.getFjcqkzs());
        updateSqsx.setFcyyzqx(hbsqsx.getFcyyzqx());
        updateSqsx.setFcyzyqx(hbsqsx.getFcyzyqx());

        updateSqsx.setFcyybqx(hbsqsx.getFcyybqx());
        updateSqsx.setFcyqtwt(hbsqsx.getFcyqtwt());
        updateSqsx.setFjcqxxm(hbsqsx.getFjcqxxm());

        updateSqsx.setFcyjl(hbsqsx.getFcyjl());
        updateSqsx.setFcyjg(hbsqsx.getFcyjg());
        updateSqsx.setFcyjcyj(hbsqsx.getFcyjcyj());

        spcySqsxBaiscMapper.update(updateSqsx, updateSxWrapper);
    }

    /**
     * 同步共用的文件记录-到每一个被合并的事项
     * */
    public void ffCommonWjjlToSubBhbSqsxByXcjc(String sqsxid, SpcySqsxBasic hbsqsx){
        if (hbsqsx == null){
            hbsqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
        }
        List<String> bhbsxids = StringPatternUtils.getListByIds(hbsqsx.getFhbsxids());

        List<String> typeCommonList = CollectionUtil.newArrayList(
                WjmlConstant.xpxcscydh,
                WjmlConstant.xpxcgcydh,
                WjmlConstant.qydwjctz,
                WjmlConstant.xcjcjl,
                WjmlConstant.wlyctsm,
                WjmlConstant.xcjcjcycns,
                WjmlConstant.xcjchyqdb,
                WjmlConstant.xcjcbg,
                WjmlConstant.xcjcbl,
                WjmlConstant.xcjcqxjlb,
                WjmlConstant.ljzlfk_cj,
                WjmlConstant.ljzlfk_fcj,
                WjmlConstant.khmyddc,
                WjmlConstant.cjcygzlfzdcb,
                WjmlConstant.sycfhxjcbg
        );
        List<SpcySqsxWjjl> hbWjList = spcySqsxWjjlService.findWjjlListByFwjlx1(typeCommonList, sqsxid);

        List<SpcySqsxWjjl> bhbSxWjList = new ArrayList<>();
        for (String bhbsxid : bhbsxids) {
            for (int i = 0; i < hbWjList.size(); i++) {

                if (hbWjList.get(i).getFwjlx().equalsIgnoreCase(".doc")
                        || hbWjList.get(i).getFwjlx().equalsIgnoreCase(".docx")){
                    /** 迁移文件和记录 */
                    this.convertMoveSqsxFile(hbWjList.get(i), bhbsxid);

                }else {

                    SpcySqsxWjjl bhbSxWj = new SpcySqsxWjjl();
                    BeanUtil.copyProperties(hbWjList.get(i), bhbSxWj);
                    bhbSxWj.setId(GetUuIdUtils.NotReplaceUuId());
                    bhbSxWj.setFwjlx6(SpcyCommonConstant.QY_WJCL_FBZ_HBSX);
                    bhbSxWj.setFpid(bhbsxid);
                    bhbSxWj.setCreateTime(new Date());

                    bhbSxWjList.add(bhbSxWj);
                }
            }
        }

        if (CollectionUtil.isEmpty(bhbSxWjList)){
            return;
        }
        // 批量插入被合并申请事项文件记录
        spcySqsxWjjlService.batchInsertBhbsxWjjlList(bhbSxWjList);
    }

    /**
     * 合并事项-审批提交后
     * 将被合并申请事项恢复在办
     * @param sqsxid 合并的事项id
     */
    private void bhbsxRecoveryFlczt(String sqsxid){
        /** 被合并申请事项 */
        LambdaUpdateWrapper<SpcySqsxBasic> updateSxWrapper = new LambdaUpdateWrapper<>();
        updateSxWrapper.eq(SpcySqsxBasic::getFhbsxids, sqsxid);

        SpcySqsxBasic updateSqsx = new SpcySqsxBasic();
        updateSqsx.setFlczt(SpcyFlowConstant.LCZT_SXLCZB);
        updateSqsx.setFzwxtzgzt("");
        spcySqsxBaiscMapper.update(updateSqsx, updateSxWrapper);

        /** 合并事项办结 */
        LambdaUpdateWrapper<SpcySqsxBasic> updateHbsxWrapper = new LambdaUpdateWrapper<>();
        updateHbsxWrapper.eq(SpcySqsxBasic::getId, sqsxid);

        SpcySqsxBasic updateHbsx = new SpcySqsxBasic();
        updateHbsx.setFlczt(SpcyFlowConstant.LCZT_SXGQ);
        updateSqsx.setFzwxtzgzt("");
        spcySqsxBaiscMapper.update(updateHbsx, updateHbsxWrapper);
    }

    /**
     * 唤起被合并申请事项的综合评定环节待办
     */
    @Transactional(rollbackFor = Exception.class)
    public Result bhbsxRecoveryZhpdJobByXcjc(String sqsxid, SpcySqsxBasic hbsqsx, SpcySqsxJob nowJob, String opinion, String submitType){
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)) {
            return Result.ok();
        }

        if (hbsqsx == null){
            hbsqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
        }

        // 指定方案环节
        SysFlowNode flowNode = this.getFlowNodeInCommon(sqsxid, SpcyFlowConstant.HJMC_ZHPD);
        if (flowNode == null){
            return Result.error("流程环节配置不存在");
        }

        /** 被合并事项的各人主办人 */
        List<String> bhbsxids = StringPatternUtils.getListByIds(hbsqsx.getFhbsxids());
        List<SqsxHbsxZbrVo> zbrsxList = spcySqsxBaiscMapper.selectFzbrListByIds(bhbsxids);
        if (CollectionUtil.isEmpty(zbrsxList)){
            return Result.error("没有相关的事项数据！");
        }

        String flcmc = "";
        if (StringUtils.isNotBlank(nowJob.getFlcmc())){
            flcmc = nowJob.getFlcmc();
        }else {
            flcmc = SpcyFlowConstant.LCMC_LIKE_SPCYLC;
        }

        List<SpcySqsxJob> newJobList = new ArrayList<>();
        for (SqsxHbsxZbrVo zbrVo : zbrsxList){
            newJobList.add(
                    flowNodeService.copyGenJob(
                            zbrVo.getId(), flowNode.getId(), flowNode.getFjdmc(),
                            zbrVo.getFzbr(), zbrVo.getFjbrmc(),
                            null, GetCurrentUserUtils.getCurrentUser(),
                            "", "",
                            "", SpcyConstant.BLZT_DB, flcmc)
            );
        }

        boolean flag = spcySqsxJobService.saveBatch(newJobList);
        if (!flag){
            return Result.error("数据插入错误！");
        }

        /** 办结事项 */
        Result result = flowNodeService.doJob(nowJob, opinion);
        if (!result.isSuccess()){
            log.error("唤起被合并申请事项的综合评定环节待办失败：{}", result.getMessage());
        }

        return Result.ok();
    }

    /**
     * 合并事项-现场检查 退回到 方案审批
     */
    public Result returnHbsxInXcjc(String sqsxid, String jobid){


        return Result.ok();
    }

    /**
     * 合并申请事项-初始化检查方案
     * @param sqsxid 合并事项id
     * @param bhbsqsxids 被合并事项ids
     */
    public void initHbsxWjjl(String sqsxid, String type, String wjmbId, String bhbsqsxids){

        if (StringUtils.isNotBlank(bhbsqsxids)) {
            /*List<String> bhbsxIds = StringPatternUtils.getListByIds(bhbsqsxids);
            List<SpcySqsxBasic> bhbsxList = spcySqsxBaiscService.listByIds(bhbsxIds);*/

            // 获取被合并事项的事项名称
            List<String> idsList = StringPatternUtils.getListByIds(bhbsqsxids);
            List<String> sxmcList = spcySqsxBaiscMapper.selectFsxmcListByIds(idsList);
            String fsxmc = ""; // 最新合并的事项名称
            for (String b : sxmcList){
                if (org.apache.commons.lang3.StringUtils.isNotBlank(fsxmc)){
                    fsxmc += "-";
                }
                fsxmc += b;
            }

            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
            if (sqsx == null){
                throw new BusinessException("没有相匹配的事项数据！");
            }

            Result result = this.initHbsxWjjlHandler(sqsxid, sqsxid, type, wjmbId, sqsx, sqsx.getFywflcode(), bhbsqsxids, fsxmc);
            if (!result.isSuccess()){
                throw new BusinessException(result.getMessage());
            }

        }else {
            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
            if (sqsx == null){
                throw new BusinessException("没有相匹配的事项数据！");
            }
            this.initHbsxWjjlHandler(sqsxid, sqsxid, type, wjmbId, sqsx, sqsx.getFywflcode(), bhbsqsxids, "");
        }

    }

    /** 初始化文件
     * @param sqsxid 合并的事项id
     * @param hbsqsxid 合并事项id
     * @param hbsqsx 合并申请事项
     * @param type 模板类型
     * @param wjmbId 模板id
     * @param fywflcode 科室业务编码
     * @param bhbsqsxids 被合并事项ids
     * @param wjxsmc 文件显示名称
     * */
    private Result initHbsxWjjlHandler(String sqsxid, String hbsqsxid, String type,
                                       String wjmbId, SpcySqsxBasic hbsqsx,
                                       String fywflcode, String bhbsqsxids, String wjxsmc){

        SpcyRsWjmb wjmb = null; //  第一个文件模板
        String wjmbUrl = ""; // 模板路径
        SqsxWjmbVo wjmbBySqsxId = busService.getHbsxWjmbBySqsxId(wjmbId, sqsxid, hbsqsx, fywflcode, type, bhbsqsxids);
        if (wjmbBySqsxId != null && StringUtils.isBlank(wjmbBySqsxId.getErrorMsg())){
            wjmbUrl = wjmbBySqsxId.getWjmbUrl();
            wjmb = wjmbBySqsxId.getWjmb();

            if (StringUtils.isBlank(type)){
                type = wjmb.getFmblx1();
            }

        }else {
            return Result.error(wjmbBySqsxId.getErrorMsg());
        }

        String destUrl = ""; //保存路径
        String wjlx = Util.getWjHz(wjmbUrl); // 获取文件路径的 文件类型

        SpcySqsxWjjl newWjjl = null;
        String sjmc = ""; // 文件虚假名称
        String wjccmc = ""; // 文件存储名称

        String newDir = "/" + DateConversionUtils.DateToMonthTwo(new Date());
        busService.initLocalTempFileMl(newDir);
        String cflj = ""; // 文件存放路径

        SpcySqsxWjjl wjjl = new SpcySqsxWjjl();
        wjjl.setFywflcode(fywflcode);
        wjjl.setFpid(sqsxid);
        wjjl.setFwjlx(wjlx);
        wjjl.setFwjlx1(type);
        wjjl.setFwjlx2(wjmb.getId());
        wjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ);

        // 被合并事项id与合并事项id不等时
        if (StringUtils.isNotBlank(bhbsqsxids)){
            wjjl.setFwjlx6(bhbsqsxids);
        }
        /*if (!sqsxid.equals(bhbsqsxid)){
            wjjl.setFwjlx6(bhbsqsxid);
        }*/

        // 文件显示名称
        if (StringUtils.isBlank(wjxsmc)) {
            String fsxmc = hbsqsx.getFsxmc();
            wjxsmc = type + "-" + fsxmc;
        }

        sjmc = GetUuIdUtils.ReplaceUuId();
        wjccmc = sjmc + wjlx;
        cflj = newDir + "/" + wjccmc;
        newWjjl = new SpcySqsxWjjl();
        BeanUtil.copyProperties(wjjl, newWjjl);

        Map map = busService.getObjectMap(hbsqsxid, hbsqsx, ""); // 获取替换相关内容

        /*String formatType = BusinessConstant.getWordFormatType(wjlx); // word替换格式
        String wordText = busService.genSqsxWj(cflj, wjlx, wjmbUrl, destUrl, formatType, map, false);*/

        String wordText = busService.genSqsxWord(sqsxid, type, cflj, wjlx, wjmbUrl, destUrl, BusinessConstant.getWordFormatType(wjlx), map, false);

        /*newWjjl.setId(GetUuIdUtils.ReplaceUuId());
        newWjjl.setFwjxsmc(wjxsmc);
        newWjjl.setFwjccmc(wjccmc);
        newWjjl.setFcflj(cflj);
        newWjjl.setFwjnr(wordText);
        newWjjl.setFbusid(sqsxid);
        newWjjl.setFbusmc(wjxsmc);
        spcySqsxWjjlService.save(newWjjl);*/
        busService.initSqsxMbWjjl(newWjjl, wjxsmc, wjccmc, cflj, wordText, sqsxid, wjxsmc);

        return Result.ok(newWjjl);
    }

    /**
     * 事项申请-文件移动
     * @param oldWjjl 旧的文件记录
     * @param newSqsxid 新的事项id
     * */
    private void convertMoveSqsxFile(SpcySqsxWjjl oldWjjl, String newSqsxid){
        String ml = "/" + DateConversionUtils.DateToMonthTwo(new Date());
        String wjccmc = newSqsxid + "-" + GetUuIdUtils.ReplaceUuId() + oldWjjl.getFwjlx();
        String newCflj = ml + "/" + wjccmc;
        busService.initLocalTempFileMl(ml);

        String absUrl = "";
        if (localFileUploadUtils.isEnableMinioWjjlFile()) {
            File file = localFileUploadUtils.convertMinioToFile(localFileUploadUtils.getSqsxWjjlRelativeUrl(oldWjjl.getFcflj()), oldWjjl.getFwjlx());
            if (file != null){
                absUrl = file.getAbsolutePath();
            }
        }else {
            absUrl = localFileUploadUtils.getSqsxWjjlAbsUrl(oldWjjl.getFcflj());
        }

        /** 复制文件 */
        if (busService.uploadMinioFileWjjl(newCflj, absUrl)){
            SpcySqsxWjjl bhbSxWj = new SpcySqsxWjjl();
            BeanUtil.copyProperties(oldWjjl, bhbSxWj);
            bhbSxWj.setId(GetUuIdUtils.NotReplaceUuId());
            bhbSxWj.setFpid(newSqsxid);
            bhbSxWj.setFwjccmc(wjccmc);
            bhbSxWj.setFcflj(newCflj);
            bhbSxWj.setFjdcflj("");

            bhbSxWj.setCreateTime(new Date());

            spcySqsxWjjlService.save(bhbSxWj);
        }
    }
}
